package com.jiong.user.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jiong.user.vo.LoginVO;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {
    private static final String TOKEN_SECRET = "jwtSECRET";
    private static final long EXPIRE_TIME = 1800L; // 单位为秒
    /**
     * 生成用户token,设置token超时时间
     *
     * @return 生成的token
     */
    public static String createToken(LoginVO loginVO) {
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_TIME * 1000);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("id", loginVO.id)
                .withExpiresAt(expireDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
        return token;
    }
    /**
     * 检验token是否正确
     * @param token 需要校验的token
     * @return 校验是否成功
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        token = token.replace("Bearer ", "");
        try {
            //设置签名的加密算法：HMAC256
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 私钥需要一致
            JWTVerifier verifier = JWT.require(algorithm).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            return null;
        }
        return jwt.getClaims();
    }
}
